﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.ReadApi.Command;
using U.B.ReadApi.Dto;
using U.B.Repistory;

namespace U.B.ReadApi.CommandHander
{
    public class GetMenudatasourceHander : IRequestHandler<GetMenudatasource, ApiResult<List<MenuTreeDto>>>
    {
        public readonly IRepistory<Menu>  _menuRepistory;
        public readonly IMapper _mapper;
        public GetMenudatasourceHander(IRepistory<Menu> menuRepistory, IMapper mapper)
        {
            _menuRepistory = menuRepistory;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<MenuTreeDto>>> Handle(GetMenudatasource request, CancellationToken cancellationToken)
        {
           ApiResult<List<MenuTreeDto>> apiResult= new ApiResult<List<MenuTreeDto>>();
            apiResult.code = Renum.显示成功;
            apiResult.Message = Renum.显示成功.ToString();
            apiResult.Data = GetMenuTreeDtos(0);
            return Task.FromResult(apiResult);
           
        }
        public List<MenuTreeDto> GetMenuTreeDtos(int PId)
        {
            var menus = _menuRepistory.GetAll().Where(x => x.PId == PId).ToList();

            var menuTreeDtos = new List<MenuTreeDto>();
            foreach (var menu in menus)
            {
                var metDtos = new MenuTreeDto();
                metDtos.Id = menu.MenuId;
                metDtos.Label = menu.MenuName;
                metDtos.MenuUrl = menu.MenusUrl;
                metDtos.Children=GetMenuTreeDtos(menu.MenuId);
                menuTreeDtos.Add(metDtos);
            }
            return menuTreeDtos;
        }
    }
}
